<template>
  <div class="app-container">
    <main-panel>
      <div class="right">
        <el-button
          size="small"
          type="success"
          icon="el-icon-plus"
          @click.native.prevent="openAddDialog"
          >新增出库规则</el-button
        >
        <el-button
          size="small"
          type="danger"
          icon="el-icon-del"
          @click.native.prevent="deleteHandle"
          :disabled="disable"
          >删除规则</el-button
        >
      </div>
    </main-panel>
    <div class="source" v-loading="listLoading">
      <vxe-grid
        :data="list"
        keep-source
        border
        resizable
        highlight-hover-row
        show-overflow
        ref="xGrid"
        style="width: 100%"
        size="mini"
        :columns="columns"
        max-height="450"
        :seq-config="{
          startIndex: (tablePage.currentPage - 1) * tablePage.pageSize
        }"
        :pager-config="tablePage"
        @page-change="handlePageChange"
        :edit-config="{
          trigger: 'dblclick',
          mode: 'cell'
        }"
        @edit-closed="closeRowMethod"
        :checkbox-config="{
          highlight: true
        }"
      >
      </vxe-grid>
    </div>
    <addGuize
      :addDialog.sync="addDialog"
      :material="material"
      :companys="express_companys"
    ></addGuize>
  </div>
</template>

<script>
import { MainPanel } from '@/components'
import { getList, edit, del, getCompanyList } from '@/api/split'
import { getMaterialList } from '@/api/sales'
import addGuize from '@/views/system/split/add.vue'
export default {
  name: 'outbound',
  data() {
    return {
      openStatus: 1,
      closeStatus: 0,
      list: [],
      material: [],
      express_companys: [],
      materialValue: null,
      listLoading: true,
      addDialog: false, // 新增
      columns: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 100,
        align: 'right',
        pageSizes: [100, 200, 500],
        layouts: [
          'Sizes',
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'FullJump',
          'Total'
        ],
        perfect: true
      },
      disable: false
    }
  },
  mounted() {},
  created() {
    this.$nextTick(() => {
      this.fetchData()
      getCompanyList().then((res) => {
        const _list = []
        for (const item of res.data) {
          _list.push({
            label: item.name,
            value: item.id
          })
        }
        this.express_companys = _list
      })
      getMaterialList().then((res) => {
        const _list = []
        for (const item of res.data.data) {
          _list.push({
            label: item.name,
            value: item.code
          })
        }
        this.material = _list
      })
    })
  },
  watch: {
    material() {
      this.$nextTick(() => {
        this.watchData()
      })
    },
    express_companys() {
      this.$nextTick(() => {
        this.watchData()
      })
    }
  },
  components: {
    MainPanel,
    addGuize
  },
  methods: {
    watchData() {
      this.columns = [
        { type: 'checkbox', width: 50, fixed: 'left' },
        {
          field: 'type',
          title: '类型',
          width: 100,
          showOverflow: true,
          formatter: this.parseStatus,
          editRender: {
            name: '$select',
            options: [
              {
                value: 'all',
                label: '全局规则'
              },
              {
                value: 'special',
                label: '特殊规则'
              }
            ],
            events: {
              change: this.changeType
            }
          }
        },
        {
          field: 'express_company_id',
          title: '快递公司',
          width: 150,
          showOverflow: true,
          formatter: this.formateCompanysName,
          editRender: {
            name: '$select',
            props: {
              options: this.express_companys,
              clearable: true
            }
          }
        },
        {
          field: 'split_weight',
          title: '拆分子单重量',
          width: 120,
          editRender: {
            name: '$input',
            props: { type: 'float', min: 0.0, max: 99999999.99, step: 0.5 }
          }
        },
        {
          field: 'material_code',
          title: '物料名称',
          width: 280,
          showOverflow: true,
          formatter: this.formateMaterialName,
          editRender: {
            name: '$select',
            props: {
              options: this.material,
              placeholder: '全局规则时此项默认为空',
              clearable: true
            }
          }
        },
        {
          field: 'description',
          title: '备注',
          width: 350,
          editRender: {
            name: 'input'
          }
        },
        { field: 'update_time', title: '最后修改时间', width: 180 },
        { field: 'update_user_name', title: '修改人', width: 180 }
      ]
    },
    fetchData() {
      getList().then((res) => {
        console.log(res)
        this.list = res.data
        this.listLoading = false
      })
    },
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.fetchData()
    },
    openAddDialog() {
      this.addDialog = true
    },
    parseStatus({ cellValue }) {
      let val = ''
      switch (cellValue) {
        case 'all':
          val = '全局规则'
          break
        case 'special':
          val = '特殊规则'
          break
      }
      return val
    },
    changeType({ row }) {
      this.saveEdit(row, 'type')
    },
    changeMaterial({ row }) {
      edit(row)
        .then((res) => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
        })
        .catch(() => {})
    },
    closeRowMethod({ row }) {
      edit(row)
        .then((res) => {
          console.log(res)
          this.$message({
            message: res.msg,
            type: 'success'
          })
        })
        .catch(() => {})
    },
    saveEdit(row, fild) {
      edit(row)
        .then((res) => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
        })
        .catch(() => {
          const grid = this.$refs.xGrid
          grid.revertData(row, fild)
        })
    },
    deleteHandle() {
      const grid = this.$refs.xGrid
      const list = grid.getCheckboxRecords() // 获取选中数据 Array
      if (list.length > 0) {
        if (list.length !== 1) {
          this.$message.error('限制单次只能删除一条规则')
          return false
        }
        this.disable = true
        const id = list[0].id
        del(id)
          .then((res) => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.disable = false
            setTimeout(() => {
              grid.remove(list)
            }, 1000)
          })
          .catch(() => {
            this.disable = false
          })
      } else {
        this.$message.error('勾选要删除的数据')
      }
    },
    formateMaterialName({ cellValue, row }) {
      if (cellValue) {
        const val = this.material.filter((item) => item.value === cellValue)
        if (val.length > 0) {
          return val[0].label
        } else {
          return '未查询到物料名称'
        }
      } else {
        return cellValue
      }
    },
    formateCompanysName({ cellValue, row }) {
      if (cellValue) {
        const val = this.express_companys.filter(
          (item) => item.value === cellValue
        )
        if (val.length > 0) {
          return val[0].label
        } else {
          return '未查询快递公司'
        }
      } else {
        return cellValue
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.source {
  padding: 24px;
  border: 1px solid #ebebeb;
  border-radius: 3px;
  transition: 0.2s;
  margin-top: 24px;
}
.table {
  width: 100%;
}
// 滚动条的宽度
/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 6px; // 纵向滚动条
}
// 滚动条的滑块
/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}
.search-form {
  width: 100%;
  .el-input {
    width: 80%;
  }
  .el-select {
    width: 80%;
    .el-option {
      width: 100%;
    }
  }
  .search {
    width: 100%;
  }
  .line {
    text-align: center;
  }
}
.right {
  text-align: right;
}
.center {
  text-align: center;
}
</style>
